package com.inspire.sms.service.impl;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.inspire.sms.config.TencentSMSConfig;
import com.inspire.sms.constant.Channels;
import com.inspire.sms.model.App;
import com.inspire.sms.model.Message;
import com.inspire.sms.model.Template;
import com.inspire.sms.exception.ChannelException;
import com.inspire.sms.model.dto.MessageDTO;
import com.inspire.sms.model.dto.QuerySendResult;
import com.inspire.sms.model.dto.SendMessageResult;
import com.inspire.sms.service.IChannelSMSService;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author inspire
 * @date 2019/7/22.
 * 具体短信通道实现类 ---> 腾讯通道
 */
@Service(Channels.TX_SMS)
public class TencentSmsServiceImpl implements IChannelSMSService {

    private static final int SUCCESS = 0;

    private static final Logger logger = LoggerFactory.getLogger(TencentSmsServiceImpl.class);

    @Autowired
    private TencentSMSConfig tencentSMSConfig;


    @Override
    public SendMessageResult send(App app, Template template, MessageDTO message) throws ChannelException {
        //构建请求对象
        SmsSingleSender ssender = new SmsSingleSender(tencentSMSConfig.getAppId(), tencentSMSConfig.getAppKey());
        SmsSingleSenderResult result = null;
        try {
            result = ssender.send(0, "86", message.getMobile(), "【腾讯云】您的验证码是: 5678", "", "");
        }catch (HTTPException e) {
            // HTTP响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        }


        if (SUCCESS == result.result) {
            return new SendMessageResult(true, result.sid);
        } else {
            logger.warn("腾讯云通讯短信发送失败,原因:{},错误代码:{},请求Id:{}", result.errMsg, result.result,
                    result.sid);
            return new SendMessageResult(Integer.toString(result.result));
        }

    }


    @Override
    public QuerySendResult querySendStatus(App app, Message message) {
        return null;
    }


    @Override
    public SendMessageResult batchSend(App app, String[] mobile, String content) throws ChannelException {
        return null;
    }


    @Override
    public String getChannel() {
        return Channels.TX_SMS;
    }
}
